﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Text.RegularExpressions;

using EraNet.Core;
using EraNet.Data;
using EraNet.Core.Model.Account;
using EraNet.Services.Account;
using EraNet.Services.SysManage;

using EraNet.Common.Files;
using EraNet.Core.Model.SysManage;
using EraNet.Common;
using EraNet.Services.Drivings;
using EraNet.Services.Test;
using EraNet.Services.Messages;
using EraNet.WebApp.AppCore;
using EraNet.Core.Model.Messages;
namespace EraNet.WebApp.LMS
{
    public class AccountController : LMSBasePage
    {
        #region Fields
        private readonly ISysCardsService _syscardService;
        private readonly IMemberService _memberService;
        private readonly ISysConfigService _sysconfigService;
        private readonly IAreaInfoService _areainfoService;
        private readonly IDriveSchoolService _driveschoolService;
        private readonly IExaminationService _examinationService;
        private readonly INoticeServices _noticeServices;
        private readonly IFeedbackServices _feedbackServices;
        #endregion

        #region Constructors
        public AccountController(ISysCardsService syscardService, IMemberService memberService, ISysConfigService sysconfigService, IAreaInfoService areainfoService, IDriveSchoolService driveschoolService,IExaminationService examinationService,INoticeServices noticeService,IFeedbackServices feedbackServices)
        {
            this._syscardService = syscardService;
            this._memberService = memberService;
            this._sysconfigService = sysconfigService;
            this._areainfoService = areainfoService;
            this._examinationService = examinationService;
            this._driveschoolService = driveschoolService;
            this._noticeServices = noticeService;
            this._feedbackServices = feedbackServices;
        }
        #endregion

        #region Methods
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 学习卡激活页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            Member member = new Member();
            return View(member);
        }

        #region 身份证登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public JsonResult MemberLogin(string userName, string pwd, string yzm, string check)
        {
            string Rmsg = string.Empty;
            #region 为空校验
            //身份证号不能为空
            if (string.IsNullOrEmpty(userName))
                return Json("1", JsonRequestBehavior.AllowGet); //Core.Model.Common.BaseMessage.Member_Name_IsNull;
            if (string.IsNullOrEmpty(pwd))
                return Json("2", JsonRequestBehavior.AllowGet);//Core.Model.Common.BaseMessage.Pwd_IsNull;
            if (string.IsNullOrEmpty(yzm))
                return Json("3", JsonRequestBehavior.AllowGet);//Core.Model.Common.BaseMessage.AuthCode_IsNull;
            if (Session["GoogleCode"] != null && yzm.ToUpper() != Session["GoogleCode"].ToString())
                return Json("4", JsonRequestBehavior.AllowGet); //Core.Model.Common.BaseMessage.AuthCode_IsNull;

            #endregion

            #region IP地址和卡号的验证
            int result = 0;//执行结果

            //验证IP对应的地市是否开放
            if (!_areainfoService.VerifyArea()) return Json("12",JsonRequestBehavior.AllowGet);
            #endregion

            //验证用户是否存在
            Member m = _memberService.GetMember(userName, pwd, out result);

            if (m != null)
            {
                //判断是否过期
                if (m.ExpireDate <= DateTime.Now)
                {
                    Session[string.Format("Member_id_{0}_uname_{1}", m.Id, m.AccountName)] = new { userName, m.Id, m.IDCard, m.SchoolID, m.ExpireDate };
                }
                //验证是否激活
                SysCards card = _syscardService.GetCardsByMemberId(m.Id);
                if (card != null)
                {
                    if (card.IsValid) //未激活
                    {
                        result = 11;
                    }
                    else
                    {
                        result = 5;
                    }
                }
                else
                {
                    result = 11;
                }
                #region 记住密码
                HttpCookie cookie = new HttpCookie("USER_COOKIE");
                if (check == "1")
                {
                    // 设置用户昵称、密码
                    cookie.Values.Add("Name", userName);

                    cookie.Values.Add("Pwd", pwd);

                    // 令 Cookie 永不过期

                    cookie.Expires = System.DateTime.Now.AddDays(7.0);

                    // 保存用户的 Cookie
                    // HttpContext.Current.Response.Cookies.Add(cookie);
                    HttpContext.Response.Cookies.Add(cookie);

                }
                else  // 若记住密码未勾选则默认这次取消记住密码，则将原本存密码的Cookies生存期设为现在，则会自动销毁
                {
                    if (Response.Cookies["USER_COOKIE"] != null)
                        Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
                }

                #endregion
                //保存登录信息
                EraNet.Common.Utility.WriteCookie("MemberModel", SerializationHelper.BtySerializer(m));
            }


            return Json(result.ToString(), JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 卡密登录
        /// <summary>
        /// 卡密登录
        /// </summary>
        /// <returns></returns>
        public JsonResult CardLogin(string cardNo, string cardPwd, string yzm, string check)
        {
            string Rmsg = string.Empty;

            #region 为空校验
            //身份证号不能为空
            if (string.IsNullOrEmpty(cardNo))
                return Json("1", JsonRequestBehavior.AllowGet); //Core.Model.Common.BaseMessage.Member_Name_IsNull;
            if (string.IsNullOrEmpty(cardPwd))
                return Json("2", JsonRequestBehavior.AllowGet);//Core.Model.Common.BaseMessage.Pwd_IsNull;
            if (string.IsNullOrEmpty(yzm))
                return Json("3", JsonRequestBehavior.AllowGet);//Core.Model.Common.BaseMessage.AuthCode_IsNull;
            if (Session["GoogleCodeCard"] != null && yzm != Session["GoogleCodeCard"].ToString())
                return Json("4", JsonRequestBehavior.AllowGet); //Core.Model.Common.BaseMessage.AuthCode_IsNull;

            #endregion
            #region IP地址和卡号的验证
            int result = 0;//执行结果

            cardNo = cardNo.ToLower();
            //验证IP对应的地市是否开放
            //暂时（屏蔽）
            if (cardNo.Substring(0, 2) != "cs" && cardNo.Substring(0, 2) != "zy")
            {
                if (!_areainfoService.VerifyArea()) return Json("12", JsonRequestBehavior.AllowGet);
            }
            #endregion

            SysCards sc = _syscardService.GetCardByNo(cardNo); 
            if(sc.IsValid)
            {
                SysCards card = _syscardService.GetCardByNo(cardNo,cardPwd);

                if (card != null) //验证学习卡是否存在
                {
                    //判断卡片是否分配
                    if (card.IsValid) //未分配给用户
                    {
                        //判断卡片是否有关联驾校
                        if (card.SchoolId != 0)
                        {
                            result = 6;
                        }
                        else
                        {
                            result = 9;
                        }
                        
                    }
                    else
                    {
                        result = 5;
                        #region 记住密码
                        HttpCookie cookie = new HttpCookie("USER_COOKIE");
                        if (check == "1")
                        {
                            // 设置用户昵称、密码
                            cookie.Values.Add("Name", cardNo);

                            cookie.Values.Add("Pwd", cardPwd);

                            // 令 Cookie 永不过期

                            cookie.Expires = System.DateTime.Now.AddDays(7.0);

                            // 保存用户的 Cookie
                            // HttpContext.Current.Response.Cookies.Add(cookie);
                            HttpContext.Response.Cookies.Add(cookie);

                        }
                        else  // 若记住密码未勾选则默认这次取消记住密码，则将原本存密码的Cookies生存期设为现在，则会自动销毁
                        {
                            if (Response.Cookies["USER_COOKIE"] != null)
                                Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
                        }

                        #endregion
                        //保存登录信息
                       
                    }
                    EraNet.Common.Utility.WriteCookie("MemberPwd", cardPwd);
                    EraNet.Common.Utility.WriteCookie("CardModel", SerializationHelper.BtySerializer(card));
                }
                else
                {
                    result = 8;
                }
            }
            else
            {
                Member m = _memberService.GetMember(cardNo, cardPwd, out result);
                if (m != null)
                {
                    EraNet.Common.Utility.WriteCookie("MemberModel", SerializationHelper.BtySerializer(m));
                    result = 5;
                }
                else
                {
                    result = 10;
                }
            }

            return Json(result.ToString(), JsonRequestBehavior.AllowGet);
        }
        #endregion

        public ActionResult CardRegister()
        {
            return View();
        }
        
        public ActionResult UserRegister(int getType=0)
        {
            SelectList schoolList = null;
            if (getType == 1)
            {
                schoolList = new SelectList(_driveschoolService.GetAllSchool(), "Id", "DrivingNames");
                
            }
            ViewData["getType"] = getType;
            ViewData["schools"] = schoolList;
            return View();
        }

        /// <summary>
        /// 学习卡激活
        /// </summary>
        /// <returns></returns>
        public JsonResult AjaxCardRegister(string cardNo, string password, string yzm)
        {
            #region 为空校验

            ///// <summary>
            ///// 获取客户端IP
            ///// </summary>
            ///// <returns></returns>
            //public string GetLocalIP()
            //{
            //    string ip = string.Empty;
            //    if (Request.ServerVariables["HTTP_VIA"] != null) // using proxy
            //    {
            //        ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
            //    }
            //    else// not using proxy or can't get the Client IP
            //    {
            //        ip = Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
            //    }
            //    return ip;
            //}

            if (Session["GoogleCode"] != null)
            {
                //如果验证码错误
                if (yzm != Session["GoogleCode"].ToString())
                {
                    return Json("4", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json("4", JsonRequestBehavior.AllowGet);
            }
            //获取登录用户
            Member m = _memberService.GetLoginMember();

            //验证卡片是否存在
            int result = _syscardService.ActiveCard(cardNo, password, m.Id);

           return Json(result.ToString(), JsonRequestBehavior.AllowGet);

            #endregion
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        public JsonResult AjaxUserRegister(string name, string idCard, string phone, string yzm,string LearnCar,int schoolId = 0)
        {
            #region 为空校验
            if (string.IsNullOrEmpty(name))
            {
                return Json("1", JsonRequestBehavior.AllowGet);//姓名不能为空字符串
            }
            if (string.IsNullOrEmpty(idCard))
            {
                return Json("2", JsonRequestBehavior.AllowGet);//身份证不能为空字符串
            }
            if (string.IsNullOrEmpty(phone))
            {
                return Json("3", JsonRequestBehavior.AllowGet);//联系电话不能为空字符串
            }
            if (string.IsNullOrEmpty(yzm))
            {
                return Json("4", JsonRequestBehavior.AllowGet);//验证码不能为空
            }
            if (string.IsNullOrEmpty(LearnCar))
            {
                return Json("12", JsonRequestBehavior.AllowGet);//验证码不能为空
            }

            if (Session["GoogleCode"] != null)
            {
                //如果验证码错误
                if (yzm.ToUpper() != Session["GoogleCode"].ToString())
                {
                    return Json("5", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json("8", JsonRequestBehavior.AllowGet);
            }
            //验证身份证格式
            if (!Common.Validator.IsIdCard(idCard))
            {
                return Json("10", JsonRequestBehavior.AllowGet);
            }
            //验证联系电话

            if (!Common.Validator.IsMobile(phone) && ! Regex.IsMatch(phone, @"(\d{3,4})-?\d{7,8}"))
            {
                return Json("11", JsonRequestBehavior.AllowGet);
            }
            #endregion

            string pwd = EraNet.Common.Utility.GetCookie("MemberPwd");

            //获取登录的学习卡
            SysCards card = _syscardService.GetLoginSysCards();
            Member member = new Member();
            member.AccountName = card.Markstr + card.CardNo;
            member.Password = Utility.MD5(pwd);
            member.Names = name;
            member.IDCard = idCard;
            member.Telephone = phone;
            member.Status = 1;
            member.Nation = "汉";
            member.Sex = "男";
            member.CreateDate = DateTime.Now;
            member.CreatedByUserID = 0;
            member.Address = "无";
            member.Email = "无";
            member.Birthday = DateTime.Now;
            member.ExpireDate = DateTime.Now.AddMonths(6);
            member.LastLoginDate = DateTime.Now;
            member.IsSuper = false;
            member.LearnCar = LearnCar;
            member.SchoolID = card.SchoolId == 0 ? schoolId : card.SchoolId;
            int result = 0;
            if (schoolId != 0)
            {
                result = _memberService.RegisterMember(member, card, schoolId, true);
                //保存登录信息
                EraNet.Common.Utility.WriteCookie("MemberModel", SerializationHelper.BtySerializer(member));
                EraNet.Common.Utility.WriteCookie("CardModel", SerializationHelper.BtySerializer(card));
            }
            else
            {
                result = _memberService.RegisterMember(member, card, schoolId, false);
                EraNet.Common.Utility.WriteCookie("MemberModel", SerializationHelper.BtySerializer(member));
                EraNet.Common.Utility.WriteCookie("CardModel", SerializationHelper.BtySerializer(card));
            }



            
            return Json(result.ToString(), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 用户信息表
        /// </summary>
        /// <returns></returns>
        public ActionResult Infos()
        {
            ViewBag.myTabId = "0";//标示tab

            var m = _memberService.GetLoginMember();
            var card = _syscardService.GetCardsByMemberId(m.Id);
            var mr=_examinationService.GetExamLogsByUser(m.Id,0,4);
            var notice = _noticeServices.SelectPager(m.SchoolID,m.Id,0, 5);
            var fb = _feedbackServices.SelectPagerByUser(m.Id, 0, 5);
            ViewBag.Member = m;
            ViewBag.Exam = mr;
            ViewBag.Notice = notice;
            ViewBag.feedback = fb;
            ViewBag.sysCard = card;
            return View();
        }


        
        
        #endregion

       
    }
}
